<?php
/**
 * Created by PhpStorm.
 * User: xiahuiqin
 * Date: 2018-09-07
 * Time: 11:05
 */

namespace App\Http\Controllers\Home\API;
use App\Http\Controllers\BaseController;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 支付逻辑
     * User: Xiahuiqin
     */
    public function recharge(Request $request)
    {
        $total_amount = $request->input('money');
        $member_id = $request->input('member_id');
        if(empty($total_amount) || empty($member_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);
        $findUser = DB::table('member')->where('id',$member_id)->where('status',1)->first();

        if(empty($findUser)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        //手机网页支付
        $config = require_once base_path().'/vendor/alipay_wap/config.php';
        require_once base_path().'/vendor/alipay_wap/wappay/service/AlipayTradeService.php';
        require_once base_path().'/vendor/alipay_wap/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';

        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $member_id.time();


        $arrs['money'] = intval($total_amount);
        $arrs['member_id'] = $member_id;
        $arrs['recharge_no'] = $out_trade_no;
        $arrs['create_time'] = time();
        $arrs['e_money'] = intval($total_amount);   //人民币转E币 TODO==
        $arrs['operate_status'] = 0;
        $arrs['type'] = 1;
        $arrs['pay_type'] = 1;
        DB::table('member_recharge')->insertGetId($arrs);

        //订单名称，必填
        $subject = 'E聊';
        //测试
//                $total_amount = '0.01';
        //商品描述，可空
        $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);

        $aop = new \AlipayTradeService($config);

        $response = $aop->wapPay($payRequestBuilder,$config['return_url'],$config['notify_url']);

        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$response]);
    }

    /**
     * 异步通知
     * User: Xiahuiqin
     * @throws \Exception
     */
    public function notify(){
        $config = require_once base_path().'/vendor/alipay_wap/config.php';
        require_once base_path().'/vendor/alipay_wap/wappay/service/AlipayTradeService.php';
        require_once base_path().'/vendor/alipay_wap/wappay/buildermodel/AlipayTradeFastpayRefundQueryContentBuilder.php';

        $arr=$_REQUEST;

        $alipaySevice = new \AlipayTradeService($config);
        $result = $alipaySevice->check($arr);

        if($result) {//验证成功
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            if($_POST['trade_status'] == 'TRADE_FINISHED') {

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                $findOrder = DB::table('member_recharge')->where('recharge_no',$out_trade_no)->first();
            }
            else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                $findOrder = DB::table('member_recharge')->where('recharge_no',$out_trade_no)->first();

            }
            if(!empty($findOrder)){
                if($findOrder->operate_status==0){
                    $arrs['paid_at'] = time();
                    $arrs['operate_status'] = 1;
                    DB::table('member_recharge')->where('id',$findOrder->id)->update($arrs);

                    $findU = DB::table('member')->where('id',$findOrder->member_id)->find();
                    $pid = $findU->pid;
                    if(!empty($pid)){
                        $findPid = DB::table('member')->where('id',$pid)->where('status',1)->find();
                        if(!empty($findPid)){
                            //插入贡献值
                            $c_insert['member_id'] = $pid;
                            $c_insert['money'] = $findOrder->e_money;
                            $c_insert['create_time'] = time();
                            $c_insert['operate_status'] = 1;
                            $c_insert['type'] = 6;
                            DB::table('member_contribution')->insertGetId($c_insert);
                        }
                    }
                }
                //获取用户信息
                $userInfo = DB::table('member')->where('id',$findOrder->member_id)->select('avatar','username')->first();
                $sendInfo['type'] = 2;
                $sendInfo['avatar'] = !empty($userInfo->avatar) ? $userInfo->avatar : '';
                $sendInfo['username'] = !empty($userInfo->username) ? $userInfo->username : '';
                $sendInfo['anchorname'] = '';
                $sendInfo['giftimage'] = '';
                $sendInfo['money'] = $findOrder->e_money;
                $help = new \Helpers();
                $help->sendJpush(json_encode($sendInfo));
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            echo "success";	//请不要修改或删除
        }else {
            //验证失败
            echo "fail";
        }
    }

    /**
     * 支付成功回调
     * User: Xiahuiqin
     * @return mixed
     * @throws \Exception
     */
    public function success(){
        $config = require_once base_path().'/vendor/alipay_wap/config.php';
        require_once base_path().'/vendor/alipay_wap/wappay/service/AlipayTradeService.php';

        $arr=$_GET;

        $alipaySevice = new \AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_GET,true));
        $result = $alipaySevice->check($arr);
        if($result) {//验证成功
            //insert sql
            $findOrder = DB::table('member_recharge')->where('recharge_no',$_GET['out_trade_no'])->first();
            if(empty($findOrder)){
                $arrs['money'] = intval($_GET['total_amount']);
                $arrs['member_id'] = substr($_GET['out_trade_no'],0,-10);
                $arrs['recharge_no'] = $_GET['out_trade_no'];
                $arrs['create_time'] = strtotime($_GET['timestamp']);
                $arrs['paid_at'] = $arrs['create_time'];
                $arrs['e_money'] = intval($arrs['money']);   //人民币转E币 TODO==
                $arrs['operate_status'] = 1;
                $arrs['type'] = 1;
                $arrs['pay_type'] = 1;
                DB::table('member_recharge')->insertGetId($arrs);

                $findU = DB::table('member')->where('id',$arrs['member_id'])->find();
                $pid = $findU->pid;
                if(!empty($pid)){
                    $findPid = DB::table('member')->where('id',$pid)->where('status',1)->find();
                    if(!empty($findPid)){
                        //插入贡献值
                        $c_insert['member_id'] = $pid;
                        $c_insert['money'] = $arrs['e_money'];
                        $c_insert['create_time'] = time();
                        $c_insert['operate_status'] = 1;
                        $c_insert['type'] = 6;
                        DB::table('member_contribution')->insertGetId($c_insert);
                    }
                }
                echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$arrs['recharge_no']]);
            }else{
                if($findOrder->operate_status==0){
                    $arrs['paid_at'] = strtotime($_GET['timestamp']);
                    $arrs['operate_status'] = 1;
                    DB::table('member_recharge')->where('id',$findOrder->id)->update($arrs);

                    $findU = DB::table('member')->where('id',$findOrder->member_id)->find();
                    $pid = $findU->pid;
                    if(!empty($pid)){
                        $findPid = DB::table('member')->where('id',$pid)->where('status',1)->find();
                        if(!empty($findPid)){
                            //插入贡献值
                            $c_insert['member_id'] = $pid;
                            $c_insert['money'] = $findOrder->e_money;
                            $c_insert['create_time'] = time();
                            $c_insert['operate_status'] = 1;
                            $c_insert['type'] = 6;
                            DB::table('member_contribution')->insertGetId($c_insert);
                        }
                    }
                    echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$_GET['out_trade_no']]);
                }else{
                    return json_encode(['code'=>-1002,'msg'=>'参数不合法']);
                }
            }
            //推送信息
            //获取用户信息
            $userInfo = DB::table('member')->where('id',$findOrder->member_id)->select('avatar','username')->first();
            $sendInfo['type'] = 2;
            $sendInfo['avatar'] = !empty($userInfo->avatar) ? $userInfo->avatar : '';
            $sendInfo['username'] = !empty($userInfo->username) ? $userInfo->username : '';
            $sendInfo['anchorname'] = '';
            $sendInfo['giftimage'] = '';
            $sendInfo['money'] = $findOrder->e_money;
            $help = new \Helpers();
            $help->sendJpush(json_encode($sendInfo));
        }
    }

    public function checkTradeNo(Request $request)
    {
        $config = require_once base_path().'/vendor/alipay_wap/config.php';
        require_once base_path().'/vendor/alipay_wap/wappay/service/AlipayTradeService.php';
        require_once base_path().'/vendor/alipay_wap/wappay/buildermodel/AlipayTradeFastpayRefundQueryContentBuilder.php';

        //商户订单号，和支付宝交易号二选一
        $out_trade_no = $request->input('trade_no');
        $RequestBuilder = new \AlipayTradeFastpayRefundQueryContentBuilder();
        $RequestBuilder->setOutTradeNo($out_trade_no);

        $Response = new \AlipayTradeService($config);
        $result=$Response->Query($RequestBuilder);

        if($result->code==10000){
            //支付成功
            echo json_encode(['code'=>1,'msg'=>'SUCCESS']);
        }else{
            //交易不存在等
            echo json_encode(['code'=>$result->code,'msg'=>$result->sub_msg]);
        }
    }


    /**
     * 支付逻辑-微信
     * User: Xiahuiqin
     */
    public function rechargeWx(Request $request)
    {
        $total_amount = $request->input('money');
        $member_id = $request->input('member_id');
//        $openId = $request->input('openid');

        if(empty($total_amount) || empty($member_id)) return json_encode(['code'=>-1002,'msg'=>'参数不合法']);
        $findUser = DB::table('member')->where('id',$member_id)->where('status',1)->first();

        if(empty($findUser)) return json_encode(['code'=>-1009,'msg'=>'数据不存在']);

        //获取微信支付类
        require_once base_path().'/vendor/wxpay/lib/WxPay.Api.php';
        require_once base_path().'/vendor/wxpay/example/WxPay.JsApiPay.php';
        require_once base_path().'/vendor/wxpay/example/log.php';

        //①、获取用户openid
//        $tools = new \JsApiPay();
//        $openId = $tools->GetOpenid();

//        $userOpenidSign = 'wxpay_openid_'.$member_id;
//        $openId = \Cache::get($userOpenidSign);
//        if(empty($openId)){
//            //手机网页支付
//            //①、获取用户openid
//            $tools = new \JsApiPay();
//            $openId = $tools->GetOpenid();
//            if(!empty($openId)){
//                \Cache::put($userOpenidSign,$openId,24*60);
//            }
//        }
        $out_trade_no = $member_id.time();
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("E聊");
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_amount*100);
//        $input->SetTime_start(date("YmdHis"));
//        $input->SetTime_expire(date("YmdHis", time() + 600));

        $input->SetSpbill_create_ip(\Request::ip());
        $input->SetNotify_url('https://eliao-tv.com/api/wx_notify');
        $input->SetTrade_type("MWEB");
//        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
//        \Log::DEBUG("recharge_query_wx:" . json_encode($order));

        //拼自己想要的
        $arrs['money'] = intval($total_amount);
        $arrs['member_id'] = $member_id;
        $arrs['recharge_no'] = $out_trade_no;
        $arrs['create_time'] = time();
        $arrs['e_money'] = intval($total_amount);   //人民币转E币 TODO==
        $arrs['operate_status'] = 0;
        $arrs['type'] = 1;
        $arrs['pay_type'] = 2;
        DB::table('member_recharge')->insertGetId($arrs);
//        echo '<script>window.location.href="'.$order['mweb_url'].'"</script>';
        $order['out_trade_no'] = $out_trade_no;
        //推送消息
        //获取用户信息
        $userInfo = DB::table('member')->where('id',$member_id)->select('avatar','username')->first();
        $sendInfo['type'] = 2;
        $sendInfo['avatar'] = !empty($userInfo->avatar) ? $userInfo->avatar : '';
        $sendInfo['username'] = !empty($userInfo->username) ? $userInfo->username : '';
        $sendInfo['anchorname'] = '';
        $sendInfo['giftimage'] = '';
        $sendInfo['money'] = intval($total_amount);
        $help = new \Helpers();
        $help->sendJpush(json_encode($sendInfo));

        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$order]);
    }

    public function wxNotify(Request $request)
    {
        require_once base_path().'/vendor/wxpay/lib/WxPay.Api.php';
        require_once base_path().'/vendor/wxpay/lib/WxPay.Notify.php';
        require_once base_path().'/vendor/wxpay/example/log.php';

        //初始化日志
        $logHandler= new \CLogFileHandler(base_path()."/vendor/wxpay/logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
//        \Log::DEBUG("begin notify");
        $notify = new \WxPayNotify();
        $notify->Handle(false);

        echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>'http://www.baidu.com']);
    }

    /**
     * 查询订单状态
     * @param Request $request
     * @return int
     * @throws \WxPayException
     */
    public function searchWxOrder(Request $request)
    {
        require_once base_path() . '/vendor/wxpay/lib/WxPay.Api.php';

        $out_trade_no = $request->input('out_trade_no');

        $input = new \WxPayOrderQuery();
        $input->SetOut_trade_no($out_trade_no);
        $returnOrder = \WxPayApi::orderQuery($input);
        if(!empty($returnOrder['trade_state']) && $returnOrder['trade_state']=='SUCCESS'){
            echo json_encode(['code'=>1,'msg'=>'SUCCESS','data'=>$returnOrder['trade_state_desc']]);
        }else{
            $msg = empty($returnOrder['err_code_des']) ? $returnOrder['trade_state_desc'] : $returnOrder['err_code_des'];
            echo json_encode(['code'=>-999,'msg'=>$msg]);
        }
    }


}